package com.bob.web.common.shiro.filter;

import com.bob.web.dao.ResourceDao;
import com.bob.web.entity.system.Resource;
import com.bob.web.util.CollectionUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 名称: ShiroResourceFilter<br>
 * 描述:资源过滤器<br>
 * 类型: JAVA<br>
 * 最近修改时间:2017/7/20 14:01<br>
 *
 * @author BoYangsh
 * @version [版本号, V1.0]
 * @since 2017/7/20 14:01
 */
public class ShiroResourceFilter extends AuthorizationFilter {

//	@Autowired
	private ResourceDao resourceDao;

	/**
	 * 公共资源存储
	 */
	public static Set<String> noAuthUris = new HashSet<>();

	/**
	 * 认证资源类型存储
	 */
	public static Set<String> authUris = new HashSet<>();

	/**
	 * 所有的资源
	 */
	public static Set<String> allUri = new HashSet<>();

	/**
	 * 页面存在
	 */
	public static  String PAGE_NOT_EXISTED = null;

	/**
	 * 用户未登录
	 */
	public static String NO_LOGIN = null;

	/**
	 * 所访问的资源未授权
	 */
	public static String NO_AUTH = null;

	/**
	 * 初始化
	 */
//	@PostConstruct
	public void init() {
		List<Resource> resources = resourceDao.findAllResources("uri");
		if(!CollectionUtil.isEmpty(resources)) {
			resources.forEach(resource -> {
				if(Resource.AUTHORITY_TYPE_PUBLIC.equals(resource.getAuthorityType())) {
					noAuthUris.add(resource.getUri());
				}else if(Resource.AUTHORITY_TYPE_AUTHENTICATION.equals(resource.getAuthorityType())) {
					authUris.add(resource.getUri());
				}
				if(Resource.TAG_404.equals(resource.getTag())) {
					this.PAGE_NOT_EXISTED = resource.getUri();
				}
				if(Resource.TAG_NO_AUTH.equals(resource.getTag())) {
					this.NO_AUTH = resource.getUri();
				}
				if(Resource.TAG_NO_LOGIN.equals(resource.getTag())) {
					this.NO_LOGIN = resource.getUri();
				}
				allUri.add(resource.getUri());
			});
		}
	}

	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
			throws Exception {
		return true;
	}
}
